package com.xm.dao.background;

import com.xm.entity.Commodity;
import com.xm.entity.CommodityGifts;
import com.xm.exception.SqlErrorException;
import com.xm.util.BaseUtil;
import org.intellij.lang.annotations.Language;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 康文程
 * @date 2024-1-16
 */
public class CommodityGiftsDao extends BaseUtil {
    /**
     * 根据commodity_gifts_id修改gifts_number
     * @param commodityGiftsId 商品礼品Id
     * @param giftsNumber 礼品数量
     * @return 修改成功返回true，失败返回false
     * @throws SqlErrorException SQL执行异常
     */
    public boolean updateGiftsNumberById(Integer commodityGiftsId, Integer giftsNumber) throws SqlErrorException {
        @Language("sql")
        String sql = "UPDATE commodity_gifts SET gifts_number = ? WHERE commodity_gifts_id = ?";
        Object[] params = {giftsNumber, commodityGiftsId};
        int result = executeUpdate(sql, params);
        return result > 0;
    }
    /**
     * 查询commodity_gifts表和commodity表联合查询结果
     * @return 包含commodity_gifts_id和commodity_name的结果集对象列表，如果不存在则返回空列表
     * @throws SqlErrorException SQL执行异常
     */
    public List<CommodityGifts> queryCommodityGiftsAndCommodity() throws SQLException {
        @Language("sql")
        String sql = "SELECT c.commodity_id,cg.commodity_gifts_id, c.commodity_name FROM commodity_gifts cg LEFT JOIN commodity c ON c.commodity_id = cg.commodity_id";
        ResultSet resultSet = executeQuery(sql);
        List<CommodityGifts> commodityGiftsList = new ArrayList<>();
        while (resultSet.next()){
            CommodityGifts commodityGifts = new CommodityGifts();
            Commodity commodity = new Commodity();
            commodity.setCommodityName(resultSet.getString("commodity_name"));
            commodity.setCommodityId(resultSet.getInt("commodity_id"));
            commodityGifts.setCommodityGiftsId(resultSet.getInt("commodity_gifts_id"));
            commodityGifts.setCommodity(commodity);
            commodityGiftsList.add(commodityGifts);
        }
        close(resultSet);
        return commodityGiftsList;
    }
}
